﻿/*
 * KLF Headless Browser
 * Written by Kris Oye <kristianoye@gmail.com>
 * Copyright (C) 2011-2012.  All rights reserved.
 */
namespace KLF.Lib.Browser.DOM.CSS.SAC.Selectors
{
    #region Using Statements

    using System;
    using System.Text;
    using KLF.Lib.Browser.DOM.HTML;
    using KLF.Lib.Browser.DOM.CSS.SAC.Conditions;

    #endregion

    public class ElementSelector : Selector
    {
        #region Constructors

        public ElementSelector()
        {
            ElementName = "*";
            MatchAny = true;
        }

        #endregion

        public static ElementSelector Any
        {
            get
            {
                return new ElementSelector()
                {
                    ElementName = "*",
                    MatchAny = true
                };
            }
        }

        public string ElementName
        {
            get
            {
                if (!String.IsNullOrEmpty(NamespaceURI))
                    return String.Format("{0}:{1}", NamespaceURI, LocalName);
                else
                    return LocalName;
            }
            set
            {
                if (!String.IsNullOrEmpty(value))
                {
                    if (value.IndexOf(':') > -1)
                    {
                        NamespaceURI = value.Substring(0, value.IndexOf(':'));
                        LocalName = value.Substring(value.IndexOf(':') + 1);
                    }
                    else
                    {
                        NamespaceURI = String.Empty;
                        LocalName = value;
                    }
                }
            }
        }

        public string LocalName { get; private set; }

        public bool MatchAny { get; private set; }

        public override bool Matches(HTMLElement e)
        {
            if (!LocalName.Equals("*"))
            {
                if (!(e.TagName.Equals(LocalName.ToLowerInvariant()) &&
                    (e.namespaceURI ?? "").Equals(NamespaceURI ?? "")))
                    return false;
            }

            foreach (Condition c in Conditions)
            {
                if (!c.MatchElement(e)) return false;
            }
            return true;
        }

        public string NamespaceURI { get; private set; }

        public override SelectorType Type
        {
            get
            {
                return SelectorType.ElementNodeSelector;
            }
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(String.Format("{0}",
                    ElementName == "" || ElementName == "*" ? "" : ElementName));

            foreach (Condition c in Conditions)
            {
                sb.Append(c);
            }

            return sb.ToString();
        }
    }
}
